package cn.zyq.ykb.system.pay.core.client.impl.alipay;


import cn.zyq.ykb.system.pay.core.client.PayCommonResult;
import cn.zyq.ykb.system.pay.core.client.dto.PayOrderUnifiedReqDTO;
import cn.zyq.ykb.system.pay.core.client.dto.PayOrderUnifiedRespDto;
import cn.zyq.ykb.system.pay.core.enums.PayChannelEnum;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;


/**
 * 支付宝【扫码支付】的 PayClient 实现类
 * 文档：https://opendocs.alipay.com/apis/02890k
 *
 * @author 芋道源码
 */
@Slf4j
public class AlipayAppPayClient extends AbstractAlipayClient {

    public AlipayAppPayClient(Integer channelId, AlipayPayClientConfig config) {
        super(channelId, PayChannelEnum.ALIPAY_APP_ANDROID.getCode(), config, new AlipayPayCodeMapping());
    }

    @Override
    public PayCommonResult<PayOrderUnifiedRespDto> doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) {
        // 构建 AlipayTradeAppPayModel 请求
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setOutTradeNo(reqDTO.getOutTradeNo());
        model.setSubject(reqDTO.getSubject());
        model.setBody(reqDTO.getBody());
        model.setTotalAmount(calculateAmount(reqDTO.getAmount()).toString()); // 单位：元
        // TODO 芋艿：userIp + expireTime
        // 构建 AlipayTradeAppPayRequest
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setBizModel(model);
        request.setNotifyUrl(reqDTO.getNotifyUrl());
        request.setReturnUrl(reqDTO.getReturnUrl());
        PayOrderUnifiedRespDto dto = new PayOrderUnifiedRespDto();
        // 执行请求
        AlipayTradeAppPayResponse response;
        try {
            response = client.sdkExecute(request);
            log.info(JSON.toJSONString(response));
        } catch (AlipayApiException e) {
            log.error("[unifiedOrder][request({}) 发起支付失败]", JSON.toJSONString(reqDTO), e);
            return PayCommonResult.build(e.getErrCode(), e.getErrMsg(), null, codeMapping);
        }
        dto.setAlipayTradeAppPayResponse(response);
        // TODO 芋艿：sub Code 需要测试下各种失败的情况
        if(response.isSuccess() && Objects.isNull(response.getCode()) && Objects.nonNull(response.getBody())){
            //成功alipay wap 成功 code 为 null , body 为form 表单
            dto.setPayReqResp(response.getBody());
            return PayCommonResult.build("-9999", "Success", dto, codeMapping);
        }else {
            return PayCommonResult.build(response.getCode(), response.getMsg(), dto, codeMapping);
        }
    }

}
